#1 {}大括号创建字典
import random

d1 = {10: 'cat', 20: 'dog', 30: 'pet', 20: 'zoo'}
print(d1) # key相同时，value值进行了覆盖
# {10: 'cat', 20: 'zoo', 30: 'pet'}

#2 zip函数映射
lst1 = [10, 20, 30]
lst2 = ['cat', 'dog', 'pet', 'zoo']
d2 = zip(lst1, lst2)
# print(d2) # 无法查看zip对象 <zip object at 0x000001E81994FC00>
print(list(d2)) # 转换成列表
# [(10, 'cat'), (20, 'dog'), (30, 'pet')]
print(dict(d2)) # 转换成字典
# {10: 'cat', 20: 'dog', 30: 'pet'}

#3 使用参数创建字典
d3 = dict(cat=10, dog=20)
print(d3)
# {'cat': 10, 'dog': 20}

t1 = (10, 20, 30) # 元组是key，10是value
print({t1: 10})
# {(10, 20, 30): 10}

# lst3 = [10, 20, 30]
# print({lst3: 10}) #报错 TypeError: unhashable type: 'list'
# # 因为列表是可变数据类型

#4 字典的删除
d4 = dict(cat=10, dog=20)
del d4

#5 字典元素的访问
d5 = dict(cat=10, dog=20)
print(d5['cat'])
# 10
print(d5.get('cat'))
# 10
#两者之间的区别：如果key不存在，d[key]报错，d.get(key)可以指定默认值
#print(d5['Java'])  # 报错
print(d5.get('Java'))
# None
print(d5.get('Java', "不存在")) # 自己设定的默认值
# 不存在

#6 字典的遍历
d6 = dict(cat=10, dog=20)
for i1 in d6.items():
    print(i1, end=' ; ') # 输出元组
# ('cat', 10) ; ('dog', 20) ;
print()

# key,value单独遍历
for key1, value1 in d6.items():
    print(key1, value1, sep=' --> ', end=' ; ')
# cat --> 10 ; dog --> 20 ;
print()
print('-'*50)

#7 字典作为可变数据类型的相关操作
d7 = {101:'zhangsan', 102:'lisi', 103:'wangwu'}
print(d7)
# {101: 'zhangsan', 102: 'lisi', 103: 'wangwu'}

# 直接赋值增加元素
d7[104] = "zhaoliu"
print(d7)
# {101: 'zhangsan', 102: 'lisi', 103: 'wangwu', 104: 'zhaoliu'}

# 获取所有的key，item, key-value键值对
keys1 = d7.keys()
print(keys1)
# dict_keys([101, 102, 103, 104])
print(tuple(keys1)) # 转换成元组
# (101, 102, 103, 104)
print(list(keys1)) # 转换成列表
# [101, 102, 103, 104]

values1 = d7.values()
print(values1)
# dict_values(['zhangsan', 'lisi', 'wangwu', 'zhaoliu'])

items1 = d7.items()
print(items1)
# dict_items([(101, 'zhangsan'), (102, 'lisi'), (103, 'wangwu'), (104, 'zhaoliu')])

# 使用pop删除key-value键值对
print(d7.pop(104))
# zhaoliu
print(d7)
# {101: 'zhangsan', 102: 'lisi', 103: 'wangwu'}
print(d7.pop(108,'不存在')) # 自己设定的默认值
# 不存在

# 随机删除
print(d7.popitem())
# (103, 'wangwu')
print(d7)
# {101: 'zhangsan', 102: 'lisi'}

# 清空字典所有元素
d7.clear()

#8 字典生成式
# 循环创建
d11 = {item11: random.randint(1,100) for item11 in range(4)}
print(d11)
# {0: 48, 1: 15, 2: 85, 3: 38}

# 映射创建
lst11 = [101, 102, 103]
lst12 = ['zhangsan', 'lisi', 'wangwu']
d12 = {key: value for value, key in zip(lst11, lst12)}
print(d12) # 颠倒key，value
# {'zhangsan': 101, 'lisi': 102, 'wangwu': 103}
d13 = {value: key for key, value in zip(lst11, lst12)}
print(d13) # 同样颠倒key，value
# {'zhangsan': 101, 'lisi': 102, 'wangwu': 103}

#9 字典属于序列，所以可以用max，len等操作